

package com.yytek.tcp.netty.tcp;


import com.yytek.common.core.constant.CacheConstants;
import com.yytek.common.redis.service.RedisService;
import com.yytek.tcp.netty.NettyServerHandler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 报文处理，需要视具体情况开发
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class NettyTcpServerHandler extends ChannelInboundHandlerAdapter {
    private static NettyTcpServerHandler nettyTcpServerHandler;

    @PostConstruct
    public void init() {
        nettyTcpServerHandler = this;
    }

    @Resource
    private NettyServerHandler nettyServerHandler;
    @Resource
    private RedisService redisService;

    /**
     * 从通道中读取信息
     * @param context
     * @param msg
     */
    @Override
    @SneakyThrows
    public void channelRead(ChannelHandlerContext context, Object msg) {
        nettyTcpServerHandler.nettyServerHandler.read(context, (ByteBuf) msg);
    }

    @Override
    @SneakyThrows
    public void exceptionCaught(ChannelHandlerContext context, Throwable throwable) {
        log.debug(throwable.getMessage());
        removeChannel(context.channel());
        context.disconnect();
    }
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        removeChannel(channel);
    }

    /**
     * 移除通道缓存
     * @param channel
     */
    public void removeChannel(Channel channel) {
        //不包含返回
        if (! NettyTcpServer.biDirectionHashMap.containsValue(channel)) {
            return;
        }
        //包含设备信息,移除设备
        NettyTcpServer.biDirectionHashMap.removeByValue(channel);
        String deviceId = NettyTcpServer.biDirectionHashMap.getByValue(channel);
        String key = CacheConstants.GW_DEVICE_CONECT_KEY+deviceId;
        redisService.deleteObject(key);
    }

}